import React from 'react';

import {inject,observer} from 'mobx-react';
import {toJS} from 'mobx';
import { withRouter,Route } from 'react-router-dom';
import { RouteLayout, Form, ListPage } from 'weaver-mobile-page';
import { List, Tools, Icon, Modal, Flex, Button, Select, Bubble } from 'weaver-mobile';
import SearchList from './searchList.js';
import Home from './home.js';
import TopBar from './topBar.js';
import { isIOS } from '../util/util';
import '../style'

const allStore =[
  'esearchStore',
]
const getLabel = Tools.getLabel;
const alert = Modal.alert;
const ButtonGroup = RouteLayout.ButtonGroup;

@inject(...allStore)
@observer
@withRouter
export default class eSearch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      searchBarType: getLabel(82857,'全部'),
      contentType: 'ALL',
      perORsysVisible: true,
      value: '',
      pIndex: 1,
      pagesize: 20,
      changeType:false,
      hideTitle: false,
      time: ''
    };
  }

  componentDidMount() {
    const { search } = this.props.location;
    let urlUuid = undefined;
    if(search !== '' ) { // 从url中获取page_uuid
      let searchParams = search.split('?')[1];
      searchParams = this.getUrl(searchParams);
      urlUuid = searchParams.page_uuid;
      const { setParams } = this.props.esearchStore;
      if(searchParams && searchParams.otherJson) {
        setParams({ urlSearchParams: searchParams,urlParams: searchParams.otherJson });
      } else {
        setParams({ urlSearchParams: searchParams });
      }
    }

    const init = () => {
      const { getBaseData,showSubmit, getCustompageBaseDatas, page_title, getAdvancedForm } = this.props.esearchStore;
      getBaseData({}, () => {
        getAdvancedForm();
      });
      showSubmit();
      // this.props.history.push('/esearch');//初始化
      // 单页传参： esearch?type=DOC&value=222&hideTitle=true
      this.search4Param(this.props.location, 'init');
      let session = JSON.parse(sessionStorage.getItem('esearchUrlParams'));
      if (session) {
        let hidetitle = session.hideTitle === 'true' ? true : false;
        if (session.type && session.hideTitle) {
          this.setState({contentType: session.type, hideTitle: hidetitle, changeType: true });
        } else if (session.type) {
          this.setState({contentType: session.type, changeType: true });
        } else if (session.hideTitle) {
          this.setState({contentType: hidetitle })
        }
      }
      let titleTemp=page_title;
      if(!page_title){
          titleTemp=getLabel('31953','微搜');
      }
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: titleTemp });
      getCustompageBaseDatas({
        cuspage_type: '1'
      });
    }

    if(urlUuid === undefined) {
      init();
    } else {
      const { setParams } = this.props.esearchStore;
      setParams({ page_uuid: urlUuid } , () => {
        init();
      });
    }
    if(window.iNoBounce && window.iNoBounce.isEnabled()) {
      isIOS() && window.iNoBounce.disable(); // 解决ios滑动问题 
    }
  }

  componentWillUnmount() {
    sessionStorage.removeItem('esearchUrlParams');
    if(window.iNoBounce && !window.iNoBounce.isEnabled()) {
      isIOS() && window.iNoBounce.enable(); // 组件卸载后，还原解决ios滑动问题时的设置
    }
  }

  componentWillReceiveProps(nextProps) {
    const { location: { pathname: nextPath, search }, history: h } = nextProps;
    const curPath = this.props.location.pathname;
    if(curPath === '/esearch' && h.action === 'POP'){
      if(window.em &&  window.em.checkJsApi('closeWindow')) {
        window.em.closeWindow();
      }
    }
    if(curPath === '/esearch/search' && nextPath === '/esearch'){
      this.setState({perORsysVisible: true});
    }
    if(curPath === '/esearch/search' && h.action === 'POP') {
      this.props.history.push(`/esearch${search}`);
    }
    // this.search4Param(nextProps.location);  
  }
  
  shouldComponentUpdate(nextProps, nextState) {
    this.changeEmTitle(nextProps);
    const { location:{ pathname, search },  history: h } = this.props;
    const { location: nP } = nextProps;
    if(h.action === 'POP' && pathname === '/esearch/search' && (nP.pathname === 'esearch')) { // 结果页返回时直接跳首页
      this.props.history.push(`/esearch${search}`);
    }
    return true;
  }

  changeEmTitle = (nextProps) => {
    const { pathname } = nextProps.location;
    const { recordParams, search_type, page_title } = nextProps.esearchStore;

    if(window.em && window.em.checkJsApi('changeTitle')) {
      let descStr = getLabel('31953','微搜');
      if(page_title){
          descStr=page_title;
      }
      if(pathname === '/esearch/commonSet') {
        descStr = getLabel('524085','常用条件设置');
      } else if(pathname === '/esearch/commonSet/add') {
        if(recordParams.key === undefined || recordParams.key === '') {
          descStr = getLabel('524266','添加常用条件');
        } else {
          descStr = getLabel('524314','编辑常用条件');
        }
      }
      window.em.changeTitle({ title: descStr });
    }
  } 


  //直接传入参数进行查询
  search4Param=(location, sType)=>{
    const URL = location.search ? location.search.split('?')[1] : ''
    const url = URL.length > 0 ? URL.split('&') : [];
    const Arr = this.getQuery(url);
    let type = location.search ? Arr['type'] : location&&location.query&&location.query.type;
    let value = location.search ? Arr['value'] : location&&location.query&&location.query.value;
    if(type!==undefined && type!==""){
      type=type.toUpperCase();
      this.state.contentType=type;
      this.setState({contentType:type,changeType:true});
      sessionStorage.setItem('esearchUrlParams', JSON.stringify(Arr))
    }
    if(value!==undefined && value!==""){
      value=decodeURI(value, "UTF-8")
      this.onTagChange(value, sType);
    }
  }

  getUrl = (search) => {
    let params = {};
    if(typeof search === 'string') {
      let arr = search.split('&');
      arr.forEach(obj => {
        let kv = obj.split('=');
        if(decodeURI) {
          params[kv[0]] = decodeURI(kv[1]);
        } else {
          params[kv[0]] = kv[1];
        }
      });
    }
    return params;
  }

  getQuery = (search)=>{
    let params ={}
    search.map((v,index)=>{
      const tempV = v.split('=');
      params[tempV[0]] = tempV[1];
      return '';
    });
    return params
  }

  onListClick = (item) => {
    // this.props.history.go(-1);
    // this.refs.seaList.scrollTop = 0; // 切换搜索类型时,重启从头开始展示
    const { setParams, onSearchClick } = this.props.esearchStore;
    const { search } = this.props.location;
    setParams({ activeKey: item.index, tabParams: item });
    onSearchClick('enter', { contentType: item.key }, this.props.history, search);
    setTimeout(() => {
      this.setState({searchBarType: item.name,contentType: item.key, pagesize: 20, pIndex: 1},() => {
        this.state.value && this.onTagChange(this.state.value, 'enter')
      });
    }, 100);
    this.resetSkipSearchParams();
  }

  resetSkipSearchParams = () => { // 重置跳转参数
    const { setParams } = this.props.esearchStore;
    setParams({
      skipSearchParams: {
        currentPage: 0,
        lastRealNumber: 0,
      }
    });
  }

  // 检索
  onTagChange = (item, type) => {
    const { doSearch, setParams, urlSearchParams } = this.props.esearchStore;
    const { contentType, pIndex} = this.state;
    const { layoutSearch } = this.props.esearchStore;
    const { search } = this.props.location;
    /** 
     * keyword: 关键字,searchType: 全文检索/标题检索,contentType:模块名,pageIndex: 当前页,
     * pageSize: 每页条数,noAuth:无权限模块,voice:是否语音
     * lastkey: 语音二次查询条件,otherjson: 其他搜索条件*/ 
    let params = {keyword: item,contentType: contentType,otherjson: '',searchType: 'CONTENT',pageIndex: pIndex,pageSize: 20}
    if (type === 'enter') { // 切换搜索类型时,重启从头开始展示
      this.refs.seaList.scrollTop = 0; 
      params = {...params, pageIndex: 1}
      this.setState({pIndex: 1});
      setParams({searchList: []});
      this.resetSkipSearchParams();
    }
    setParams({loading: true});
    if(item !== '') {
      doSearch(params);
      this.props.location.pathname !== '/esearch/search' && this.props.history.push(`${layoutSearch.path}${search}`);
      this.setState({perORsysVisible: false,value: item});
      if(urlSearchParams) {
        if(urlSearchParams.hideTitle === 'true') {
          setParams({ topbarVisible: false });
        }
        if(urlSearchParams.value && urlSearchParams.value !== '') {
          setParams({ searchInputVal: urlSearchParams.value });
        }
        if(urlSearchParams.type) {
          setParams({ tabParams: { key:  urlSearchParams.type } });
        }
      }
    }else{
      this.props.history.push('/esearch');
      this.setState({perORsysVisible: true,value: item})
    }
  }

  getList = () => {
    const { contentType, setParams, tabParams, clearExtraForm } = this.props.esearchStore;
    let field = [];
    contentType && contentType.map(item => {
      field.push({
        key: item.key,
        showname: item.name,
      })
    });
    return(
      <Select 
        className={'esearch-type-lists'}
        options={field}
        active={true}
        value={tabParams.key}
        onChange={(val, showname) => {
          let params = contentType.find(v => (v.key === val));
          let item = {
            key: val,
            name: showname,
            index: Array.isArray(contentType) ? params.index : ''
          };
          this.onListClick(item);
          setParams({ tabParams: params });
          clearExtraForm();
        }}
      />
    );
  }

  // listVisible = () => {
  //   const { layout } = this.props.esearchStore;
  //   this.props.history.push(layout.path);
  // }

  onFeedbackClick = () => {
    const { value, pagesize } = this.state;
    const { submitResult } = this.props.esearchStore;
    let params = {key: value,page: '',pageSize: pagesize,searchType: 'CONTENT',loginId: '',condition: '',sort: '',contentType: '',sourceType: '',searchField: '' };
    if(value === ''){
      alert(getLabel(558,'提示'), getLabel(391097,'您还未查询,不能提交'), [
        { text: getLabel(826,'确定'), onPress: () => {}},
      ])
    }else{
      alert(getLabel(558,'提示'), getLabel(391098,'不是我想要的答案,确认提交?'), [
        { text: getLabel(31129,'取消'), onPress: () => {} },
        { text: getLabel(826,'确定'), onPress: () => {submitResult(params)} },
      ])
    }
  }
    
  // onscroll = (e) => {
  //   const {pageCount,pageindex,isSearchStart} = this.props.esearchStore;
  //   const {pagesize,pIndex} = this.state;
  //   let listHeight = 0, scrollHeight = 0, divHeight = 0;
  //   if (document.getElementsByClassName('list-container') && document.getElementsByClassName('list-container')[0]) {
  //     listHeight = document.getElementsByClassName('list-container')[0].scrollHeight,// 列表的高度
  //     scrollHeight = this.refs.seaList.scrollTop, // 滚动的高度
  //     divHeight = this.refs.seaList.offsetHeight; // 窗口的高度
      
  //     if(listHeight-divHeight-20 <= scrollHeight) {
  //       if (!isSearchStart) return;
  //       if(parseInt(pageCount,10) > parseInt(pageindex,10)) {
  //         // 数据没请求完，上拉刷新
  //         this.setState({pIndex: pIndex+1},() => this.onTagChange(this.state.value, 'scroll'));
  //       }
  //     }
  //   }
  // }
  
  getLoading = () => {
    return <div className='esearch-loading'>
      <Icon type='loading' size='lg'/>
    </div>
  }

  promptSave = (text) => {
    if(text !== '') {
      const { doSaveSearchTag, tabParams, searchInputVal, tagParams, getCustompageBaseDatas } = this.props.esearchStore;
      let p = {
        id: tagParams.key || '',
        search_type: tabParams.key,
        tagTitle: text,
        tagName: searchInputVal || text,
        search_json: JSON.stringify(this.filterParams())
      };
      doSaveSearchTag(p, () => {
        getCustompageBaseDatas({ cuspage_type: '3', showHideTag: 1 }, () => {
          this.setState({ time: new Date().getTime()});
        });
      });
    }
  }

  saveasCommonCondition = () => {
    const { searchInputVal } = this.props.esearchStore;
    Modal.prompt(getLabel('524272','请输入条件名称') , '',
      [
        {
          text: getLabel('31129','取消') ,
          onPress: value => {},
        },
        {
          text: getLabel('826','确定'),
          onPress: value => new Promise((resolve, reject) => {
            if(value === '') {
              Bubble.error(getLabel('524259','必填项未填写!') , 1, { top: '50%' });
              reject();
            } else {
              resolve();
              this.promptSave(value);
            }
          }),
        },
      ], 'text-required', searchInputVal)

  }

  getFields = (form, btns, className) => {
    if(form === undefined) return;
    const { conditioninfo, isInit } = form;
    let fields = [];
    const onchange = (...params) => {
      const { setParams } = this.props.esearchStore;
      setParams({ tagParams: {} });
      form.onChange(...params);
      if(params && params[0] && params[0].domkey && params[0].domkey[0] ==="tagName") {
        if(window.esearch_debounce) clearTimeout(window.esearch_debounce);
        window.esearch_debounce = setTimeout(() => {// 防抖
          let formparams = form.formParams;
          if(formparams.tagTitle === '') {
            form.updateFields({ tagTitle: { value: params[1] } });
          }
        }, 500);
      }
    }
    if (isInit) {
      conditioninfo.forEach((group) => {
        group.items.forEach((field) => {
          fields.push(<Form.Item
            key={field.domkey.join('__')}
            form={form}
            fieldConfig={field}
            onChange={onchange}
          />);
        });
      });
    }

    return (
      <div className={`esearch-advance-from ${className}`} >
        <Form style={{ height: btns.length === 0 ? '100%' : 'calc(100% - 50px)' }} >
          <List>
            { fields }
          </List>
        </Form>
        {btns && btns.length > 0 && <ButtonGroup data={btns}/>}
      </div>
    );
  }

  filterParams = () => {
    let { filterAdParams } = this.props.esearchStore;
    return filterAdParams();
  }

  adSearch = () => {
    const { onSearchClick } = this.props.esearchStore;
    const { search } = this.props.location;
    let otherString = JSON.stringify(this.filterParams());
    onSearchClick('enter', { page_search_json: otherString }, this.props.history, search);
  }

  getExtraFormitems = () => {
    const { extraForm, clearExtraForm, setParams } = this.props.esearchStore;
    const btns = [
      {
        key: 'saveAsCoditon',
        text: <span className="saveas-btn">
          <div className="saveas-btn-icon"><Icon type="end" size={"xs"}/></div>
          <div className="saveas-btn-label">{getLabel('524258','存为常用条件') }</div>
        </span>,
        onClick: () => {
          this.saveasCommonCondition();
        },
      },
      {
        key: 'reset',
        className: 'reset-btn',
        text: getLabel('2022','重置') ,
        onClick: () => { 
          clearExtraForm();
          setParams({ tagParams: {} });
        },
      },
      {
        key: 'search',
        text: getLabel('388113','搜索') ,
        type: 'primary',
        onClick: () => { this.adSearch() },
      },
    ];
    return this.getFields(extraForm, btns);
  }

  delete = (msg, ok, oncacel) => {
    alert(getLabel(558,'提示'), msg || getLabel('524273','确定删除？'), [
      { text: getLabel(826,'确定'), onPress: () => {
        typeof ok === 'function' && ok();
      }},
      { text: getLabel(386789,'取消'), onPress: () => {
        typeof oncacel === 'function' && oncacel();
      }},
    ])
  }

  getCommonSetForms = () => {
    let { addCommonSetLayout, getSearchTagDtl, homeBaseDatas:{tagList}, 
      delSearchTag, getCustompageBaseDatas, showAndHideSearchTag, setParams, addCommonSetForm
    } = this.props.esearchStore;
    const { search } = this.props.location;

    tagList = toJS(tagList); 
    const _this = this;
    const template1 = {
      default: [
        {
          key: 'col1',
          style: { flex: 'none' },
          render(res) {
            if(res.canDel) return <Icon type="editor" style={{ color: '#333', width: 18, height: 18, verticalAlign: 'middle' }} onClick={() => {
              setParams({ recordParams: res });
              getSearchTagDtl({ id: res.key }, () => {
                _this.props.history.push(`${addCommonSetLayout.path}${search}`);
              });
            }}/>;
          },
        },
        {
          key: 'col2',
          className: 'e-item',
          configs: [
            { key: 'row1', configs: [{ key: 'name' }] },
          ],
        },
      ],
    };
    return(
      <div className="esearch-commonset" taglist={tagList} time={this.state.time}>
        <div className="esearch-commonset-top">
          <Button className="esearch-commonset-top-btn" color={'#00A9FF'} 
            onClick={() => {
              setParams({ recordParams: {} });
              getSearchTagDtl({}, () => {
                this.props.history.push(`${addCommonSetLayout.path}${search}`);
              });
            }}
          > <Icon type="plus"/> {getLabel('524266','添加常用条件') }</Button>
        </div>
        <div className="esearch-commonset-list">
          <List>
            {tagList && tagList.map((res, i) => {
              let right = [];
              if(res.canDel) {
                right.push({
                  text: getLabel('501169','编辑') ,
                  onPress: () => {
                    setParams({ recordParams: res });
                    getSearchTagDtl({ id: res.key }, () => {
                      _this.props.history.push(`${addCommonSetLayout.path}${search}`);
                    });
                  },
                  style: { backgroundColor: '#4878D3', color: 'white' },
                });
              }
              right.push({
                text: res.enable === '0' ? getLabel('25424','取消隐藏') : getLabel('16636','隐藏') ,
                onPress: () => {
                  if(res.enable === '1') { // 隐藏
                    showAndHideSearchTag({ id: res.key , enable: 0 }, () => {
                      getCustompageBaseDatas({ cuspage_type: '3', showHideTag: 1 }, () => {
                        this.setState({ time: new Date().getTime()});
                      });
                    });
                  } else { // 取消隐藏
                    showAndHideSearchTag({ id: res.key , enable: 1 }, () => {
                      getCustompageBaseDatas({ cuspage_type: '3', showHideTag: 1 }, () => {
                        this.setState({ time: new Date().getTime()});
                      });
                    });
                  }
                },
                style: { backgroundColor: '#999', color: 'white' },
              });
              if(res.canDel) {
                right.push({
                  text: getLabel(91,'删除'),
                  onPress: () => { 
                    let msg = `${getLabel('524274','确认删除：')}${res.name} ?`;
                    this.delete(msg, () => {
                      delSearchTag({ id: res.key },() => {
                        getCustompageBaseDatas({ cuspage_type: '3', showHideTag: 1 }, () => {
                          this.setState({ time: new Date().getTime()});
                        });
                      });
                    });
                  },
                  style: { backgroundColor: '#F4333C', color: 'white' },
                });
              }
              return <ListPage.Item 
                key={res.key+res.enable}
                template={template1}
                data={res}
                // store={commonSetListStore}
                withSwipeAction={true}
                swipeActionProps={    
                  {right: right}
                }     
                extra={<Icon type="more-3"/>}
                onRowClick={(...arg) => {
                  // const { pathname } = this.props.location;
                  
                }}
              /> 
            })}
          </List>
        </div>
        {/* <div className="esearch-commonset-btn">
          <Button type="primary"> 确定</Button>
        </div> */}
      </div>
    );
  }

  addCommonSetFormSave = () => {
    let { addCommonSetForm, doSaveSearchTag, browserKeyArr, getCustompageBaseDatas, recordParams, filterAdParams1 } = this.props.esearchStore;
    const result = addCommonSetForm.doValidate();
    if(result.pass) {
      const formParams = addCommonSetForm.formParams;
      let search_json = filterAdParams1(addCommonSetForm, browserKeyArr);
      search_json = toJS(search_json);
      let bool = false;
      if(formParams.CREATERID_select && String(formParams.CREATERID_select.CREATERID_select) === '2' ) { // 创建人
        let temp = toJS(search_json.CREATERID);
        if(temp === undefined) {
          bool = true;
        } else if(temp.length === 0){
          bool = true;
        }
      }
      if(String(search_json.CREATEDATE_date_select) === '5') {
        if(search_json.CREATEDATE_range_picker_start === undefined || search_json.CREATEDATE_range_picker_end === undefined || 
          search_json.CREATEDATE_range_picker_start === '' || search_json.CREATEDATE_range_picker_end === '') {
          bool = true;
        }
      }
      if(bool) {
        Bubble.error(getLabel('524259','必填项未填写!') , 1, { top: '50%'});
        return;
      }
      if(String(search_json.CREATEDATE_date_select) === '5' && search_json.CREATEDATE_range_picker_start !== undefined && search_json.CREATEDATE_range_picker_end !== undefined) {
        if(search_json.CREATEDATE_range_picker_start > search_json.CREATEDATE_range_picker_end) {
          Bubble.error(getLabel('524275','开始时间应小于结束时间！'), 1, { top: '50%'});
          return;
        }
      }
      
      let p = {
        ...formParams, 
        id: recordParams.key,
        search_json: JSON.stringify(search_json)
      };

      doSaveSearchTag(p, () => {
        getCustompageBaseDatas({ cuspage_type: '3', showHideTag: 1 }, () => {
          this.props.history.go(-1);
          this.setState({ time: new Date().getTime() });
        });
      });
    }
  }

  getAddOrEditCommonSetForms = () => {
    const { addCommonSetForm } = this.props.esearchStore;
    const btns = [
      {
        key: 'submit',
        text: getLabel('826','确定') ,
        type: 'primary',
        onClick: this.addCommonSetFormSave,
      },
    ];
    return this.getFields(addCommonSetForm, btns);
  }

  render() {
    let { layout, extraLayout, commonSetLayout,
      searchResultLayout, addCommonSetLayout,topbarVisible
    } = this.props.esearchStore;
    return (
      <Flex className="esearch-home-container">
        <div>
          <Home />
        </div>
        <Route
          key={layout.id}
          path={layout.path}
          render={() => (
            <RouteLayout>
              <div
                key='tablist'
                className="wm-route-layout esearch-tablist"
                >
                  {this.getList()}
                  <div className="esearch-tablist-bottom" onClick={() => {this.props.history.go(-1)}}>
                  </div>
              </div>
            </RouteLayout>
          )}
        />
        <Route
          key={searchResultLayout.id}
          path={searchResultLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key='result'
                className="wm-route-layout esearch-result"
              >
                <TopBar />
                <SearchList height={topbarVisible ? 'calc(100% - 93px)' : 'calc(100% - 45px)'} location={this.props.location}/>
              </div>
            </RouteLayout>
          )}
        />
        <Route
          key={extraLayout.id}
          path={extraLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key='extraCondition'
                className="wm-route-layout esearch-extraCondition"
                >
                  {this.getExtraFormitems()}
              </div>
            </RouteLayout>
          )}
        />
        <Route
          key={commonSetLayout.id}
          path={commonSetLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key='commonConditionSet'
                className="wm-route-layout esearch-commonConditionSet"
              >
                {this.getCommonSetForms()}
              </div>
            </RouteLayout>
          )}
        />
        <Route
          key={addCommonSetLayout.id}
          path={addCommonSetLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key='addCommonSetLayout'
                className="wm-route-layout esearch-addCommonSetLayout"
              >
                { this.getAddOrEditCommonSetForms()}
              </div>
            </RouteLayout>
          )}
        />
        {/* { initLoading && this.getLoading() } */}
      </Flex>
    );
  }
}
